package com.moli.iov.base.remote.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.moli.iov.base.constants.SysConstants;
import com.moli.iov.base.enums.AttentionStatusEnum;
import com.moli.iov.base.enums.AuthorizedEnum;
import com.moli.iov.base.enums.DictTypeTag;
import com.moli.iov.base.enums.InstallStatusEnum;
import com.moli.iov.base.enums.OnLineStatusEnum;
import com.moli.iov.base.enums.PositioningStateEnum;
import com.moli.iov.base.enums.QueryParamEnum;
import com.moli.iov.base.model.VehicleAttentionParam;
import com.moli.iov.base.model.dto.VehicleCommand;
import com.moli.iov.base.model.dto.req.QueryVehicleBaseListReqDto;
import com.moli.iov.base.model.dto.req.VehicleBaseAuthDto;
import com.moli.iov.base.model.dto.req.VehicleBaseReqDto;
import com.moli.iov.base.model.dto.req.VehicleGraphicsQueryListReqDto;
import com.moli.iov.base.model.dto.res.VehicleBaseQueryListResDto;
import com.moli.iov.base.model.dto.res.VehicleBaseResDto;
import com.moli.iov.base.model.dto.res.VehicleGraphicsQueryListResDto;
import com.moli.iov.base.model.po.VehicleAttention;
import com.moli.iov.base.model.po.VehicleBase;
import com.moli.iov.base.model.po.VehicleBaseAuth;
import com.moli.iov.base.remote.IVehicleBaseRemoteService;
import com.moli.iov.base.service.*;
import com.moli.iov.base.util.CollectionUtils;
import com.moli.iov.base.util.PageUtils;
import com.moli.iov.base.util.ServiceValidation;
import com.moli.iov.enums.UserTypeEnum;
import com.moli.iov.exception.BusinessException;
import com.moli.iov.notify.remote.INoticeMessageCenterRemoteService;
import com.moli.iov.real.model.res.VehicleStatusDto;
import com.moli.iov.real.service.IRealService;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.sys.model.po.User;
import com.moli.iov.sys.remote.IUserRemoteService;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.JsonUtils;
import com.moli.iov.util.StringUtil;
import com.moli.iov.util.ValidationUtils;

import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业务处理
 *
 * @author whl
 */
@Transactional(rollbackFor = Exception.class)
@Service(group = "${service.group}")
@Slf4j
public class IVehicleBaseRemoteServiceImpl implements IVehicleBaseRemoteService {

    @Autowired
    private IVehicleBaseService iVehicleBaseService;
    @Autowired
    private IVehicleTboxService iVehicleTboxService;
    @Autowired
    private IDictDataService dictDataService;
    @Autowired
    private ICompanyVehicleModelService iCompanyVehicleModelService;
    @Autowired
    private IVehicleAttentionService iVehicleAttentionService;

    @Autowired
    private IVehicleFollowGroupService iVehicleFollowGroupService;

    @Reference(group = "${service.group}", check = false, timeout = 10000)
    private IUserRemoteService userRemoteService;

    @Reference(group = "${service.group}", check = false, timeout = 10000)
    private IRealService iRealService;

    @Reference(group = "${service.group}", check = false, timeout = 10000)
    private INoticeMessageCenterRemoteService iNoticeMessageCenterRemoteService;

    @Autowired
    private IVehicleBaseAuthService baseAuthService;

    final String DEFAULT_ATTENTION = "默认关注";

    @Override
    public RestResponse onlineRemind(String vin) {
        try {
            VehicleAttentionParam vehicleAttentionParam = new VehicleAttentionParam();
            vehicleAttentionParam.queryInVin(Arrays.asList(new String[]{vin}));

            List<VehicleAttention> vehicleAttentionList = iVehicleAttentionService.list(vehicleAttentionParam.get());
//            List<Long> userIdList = vehicleAttentionList.stream().filter(vehicleAttention ->
//                    vehicleAttention.getOnlineReminder().intValue() == 0).map(vehicleAttention ->
//                    vehicleAttention.getUserId()).collect(Collectors.toList());

            if(vehicleAttentionList!=null && vehicleAttentionList.size()>0){
                List<Long> userIdList = new ArrayList<>();
                for (VehicleAttention vehicleAttention : vehicleAttentionList) {
                    if(vehicleAttention!=null
                            && StringUtil.isNotBlank(vehicleAttention.getVin())
                            && vehicleAttention.getOnlineReminder()!=null
                            && vehicleAttention.getOnlineReminder()!=0){
                        userIdList.add(vehicleAttention.getUserId());
                    }
                }


                RestResponse<List<User>> restResponse = userRemoteService.findByUserIdList(userIdList);
                if (RestResponse.isSuccess(restResponse)) {
                    List<User> userList = restResponse.getData();
                    String emailTos = userList.stream().map(user -> user.getEmail()).collect(Collectors.joining(","));
                    return iNoticeMessageCenterRemoteService.sendTo(emailTos, vin);
                }
            }

        }catch (Exception ex){
            ex.printStackTrace();
            return RestResponse.failure(ex.getMessage());
        }
        return RestResponse.success();
    }

    @Override
    public RestResponse saveVehicleBase(VehicleBaseReqDto dto) {
        log.info("车辆监控 - 车辆管理-列表-添加车辆-入参VehicleBaseReqDto:{}" ,JsonUtils.toJson(dto));
        ValidationUtils.validateBean(dto, VehicleBaseReqDto.Save.class);
        Date time = Calendar.getInstance().getTime();
        //公司设置
        if (UserTypeEnum.COMPANY.getFlag() == dto.getSysUserType().intValue()) {
            dto.setCompanyId(dto.getSysCompanyId());
            dto.setCompanyName(dto.getSysCompanyName());
        }
        setBrandAndSeries(dto);
        //设置
        dto.setAuthorizedStatus(AuthorizedEnum.AUTHORIZED.getCode());
        dto.setCreateUser(dto.getCreateUser());
        dto.setGmtCreate(time);
        dto.setGmtModified(time);
        dto.setCreateUser(dto.getSysUserId().toString());
        dto.setModifiedUser(dto.getSysUserId().toString());
        RestResponse restResponse = iVehicleBaseService.saveVehicleBase(dto);
        if (restResponse.flag){
            saveVehicleBaseAuth(dto);
        }
        log.info("车辆监控 - 车辆管理-列表-添加车辆-出参RestResponse:{}" ,JsonUtils.toJson(restResponse));
        return restResponse;
    }
    /**
     * 添加车辆授权状态 初始化
     * @param dto
     */
    public void saveVehicleBaseAuth(VehicleBaseReqDto dto){
        Date date = Calendar.getInstance().getTime();
        VehicleBaseAuth auth=new VehicleBaseAuth();
        auth.setLoginAuthStatus(AuthorizedEnum.AUTHORIZED.getCode());
        auth.setLostAlarmAuthStatus(AuthorizedEnum.AUTHORIZED.getCode());
        auth.setMileageAlarmAuthStatus(AuthorizedEnum.AUTHORIZED.getCode());
        auth.setTerminalAuthStatus(AuthorizedEnum.AUTHORIZED.getCode());
        auth.setFenceAlarmAuthStatus(AuthorizedEnum.AUTHORIZED.getCode());
        auth.setGmtCreate(date);
        auth.setCreateUser(dto.getSysUserId().toString());
        auth.setVin(dto.getVin());
        baseAuthService.saveVehicleBaseAuth(auth);
    }
    @Override
    public VehicleBase getVehicleBaseByVin(String vin) {
        return iVehicleBaseService.getVehicleBaseByVin(vin);
    }

    @Override
    public RestResponse updateVehicleBase(VehicleBaseReqDto dto) {
        log.info("车辆监控 - 车辆管理-列表-更新车辆-入参VehicleBaseReqDto:{}" ,JsonUtils.toJson(dto) );
        ValidationUtils.validateBean(dto, VehicleBaseReqDto.Update.class);
        setBrandAndSeries(dto);
        Date time = Calendar.getInstance().getTime();
        dto.setGmtModified(time);
        dto.setModifiedUser(dto.getSysUserId().toString());
        RestResponse restResponse = iVehicleBaseService.updateVehicleBase(dto);
        log.info("车辆监控 - 车辆管理-列表-更新车辆-出参RestResponse:{}" ,JsonUtils.toJson(restResponse) );
        return restResponse;
    }

    /**
     * 设置品牌 车系 车型
     */
    private void setBrandAndSeries(VehicleBaseReqDto dto) {
        List<DictTypeTag> list = new ArrayList<>();
        list.add(DictTypeTag.VEHICLE_SERIES);
        list.add(DictTypeTag.VEHICLE_TYPE);
        list.add(DictTypeTag.BRAND);
        Map<String, Map<String, String>> dictMaps = dictDataService.getDictMaps(list);
        dto.setVehicleSeriesName(
                dictMaps.get(DictTypeTag.VEHICLE_SERIES.getType()).get(dto.getVehicleSeries()));
        dto.setVehicleTypeName(
                dictMaps.get(DictTypeTag.VEHICLE_TYPE.getType()).get(dto.getVehicleType()));
        dto.setBrandName(dictMaps.get(DictTypeTag.BRAND.getType()).get(dto.getBrand()));
    }

    @Override
    public List<VehicleBase> listVehicleBase() {
        return iVehicleBaseService.listVehicleBase();
    }

    @Override
    public List<VehicleBase> listVehicleBaseByCompanyId(Long companyId) {
        return iVehicleBaseService.listVehicleBaseByCompanyId(companyId);
    }

    @Override
    public RestResponse queryAttentionGroup(Long userId) {
        try {
            Map<Long, String> vehicleFollowGroupMap = iVehicleFollowGroupService.findNameByUserId(userId);
            List<Map<String, String>> result = vehicleFollowGroupMap.entrySet().stream().map(entry -> new HashMap<String, String>(2) {{
                put("dictCode", entry.getKey().toString());
                put("dictValue", entry.getValue());
            }}).collect(Collectors.toList());
            return RestResponse.success(result);
        }catch(Exception ex){
            return RestResponse.failure(ex.getMessage());
        }
    }

    @Override
    public RestResponse queryAttentionVehicleGraphics(VehicleGraphicsQueryListReqDto reqDto) {
        log.info("车辆监控 - 车辆管理-图形树入参VehicleGraphicsQueryListReqDto:{}" + JSONObject.toJSONString(reqDto));
        ValidationUtils.validateBean(reqDto);
        try {
            Instant instant = Instant.now();
            Map<String, Set<String>> followGroupList = iVehicleFollowGroupService.findVehicleFollowGroupByUserId(reqDto.getSysUserId());
            Map<Long, String> vehicleFollowGroupMap = iVehicleFollowGroupService.findNameByUserId(reqDto.getSysUserId());
            if (followGroupList == null || followGroupList.isEmpty()) {
                if(vehicleFollowGroupMap!=null && vehicleFollowGroupMap.size()>0){
                    Map map = new HashMap();
                    map.put("total",0);
                    List<Map> list = new ArrayList<>();
                    List empty = new ArrayList();
                    for (Map.Entry<Long, String> entry : vehicleFollowGroupMap.entrySet()) {
                        Map childMap = new HashMap();
                        childMap.put("province",entry.getValue());
                        childMap.put("id",entry.getKey());
                        childMap.put("list",empty);
                        list.add(childMap);
                    }
                    map.put("list", list);
                    return RestResponse.success(map);

                }
                return RestResponse.success();
            }
            Map<String,Long> vehicleFollowGroupNameIdMap = new HashMap<>();
            for (Map.Entry<Long, String> entry : vehicleFollowGroupMap.entrySet()) {
                vehicleFollowGroupNameIdMap.put(entry.getValue(),entry.getKey());
            }

            VehicleAttentionParam vehicleAttentionParam = new VehicleAttentionParam();
            vehicleAttentionParam.queryEqUserId(reqDto.getSysUserId());
            List<VehicleAttention> vehicleAttentionList = iVehicleAttentionService.list(vehicleAttentionParam.get());
            Map<String, Integer> onlineReminderMap = new HashMap<>();
            if (vehicleAttentionList!=null && vehicleAttentionList.size()>0) {
                for (VehicleAttention vehicleAttention : vehicleAttentionList) {
                    if(vehicleAttention!=null && vehicleAttention.getOnlineReminder()!=null && StringUtil.isNotBlank(vehicleAttention.getVin())){
                        onlineReminderMap.put(vehicleAttention.getVin(),vehicleAttention.getOnlineReminder());
                    }
                }
            }
            List<String> vehicleNumberConditionList = new ArrayList<>();
            followGroupList.values().stream().forEach(followGroup -> vehicleNumberConditionList.addAll(followGroup));
            List<VehicleBase> baseList = new ArrayList<>();
            if(vehicleNumberConditionList.size()>0){
                baseList = iVehicleBaseService.lisVehicleBaseByVin(vehicleNumberConditionList).stream().collect(Collectors.toList());
                if (CollectionUtils.isEmpty(baseList)) {
                    return RestResponse.success();
                }
            }

            //得到所有的在线的车架号
            RestResponse<List<String>> onlineRestResponse = iRealService.queryAllOnlineList();
            ServiceValidation.validationService(onlineRestResponse, SysConstants.IOV_SERVICE_REAL);
            //得到tbox 生产厂商+终端型号
            Map<String, String> tboxModelMap = iVehicleTboxService.listVehicleTboxModelMap();
            //企业车机型号指令集合
            Map<String, String> commandMap = iCompanyVehicleModelService.listVehicleCommandMap();
            //得到所有的 定位状态
            //TODO  提供查找所有定位
            RestResponse<Map<String, Boolean>> locationVinMap = iRealService.isLocationVinMap(
                    baseList.stream().map(VehicleBase::getVin).collect(Collectors.toList()));
            ServiceValidation.validationService(locationVinMap, SysConstants.IOV_SERVICE_REAL);
            //拼装结果集
            List<VehicleGraphicsQueryListResDto> results = new ArrayList<>();

            if (UserTypeEnum.COMPANY.getFlag() == reqDto.getSysUserType().intValue()) {
                reqDto.setCompanyId(reqDto.getSysCompanyId());
                reqDto.setCompanyName(reqDto.getSysCompanyName());
            }
            //平台用户并且公司Id为空
            if (UserTypeEnum.PLATFORM.getFlag() == reqDto.getSysUserType().intValue() && null == reqDto
                    .getCompanyId()) {
                results = filterAttentionVehicleGraphics(baseList, followGroupList, vehicleFollowGroupMap, tboxModelMap, commandMap, onlineRestResponse, locationVinMap, onlineReminderMap, reqDto);
            } else {
                //企业用户 或者是 平台用户按公司查询
                List<VehicleBase> collect = baseList.stream().filter(
                        vehicleBase -> reqDto.getCompanyId().longValue() == vehicleBase.getCompanyId().longValue()).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(collect)) {
                    return RestResponse.success();
                }
                results = filterAttentionVehicleGraphics(collect, followGroupList, vehicleFollowGroupMap, tboxModelMap, commandMap, onlineRestResponse, locationVinMap, onlineReminderMap, reqDto);
            }
            if (results.isEmpty()) {
                RestResponse.success();
            }

            Map<String, List<VehicleGraphicsQueryListResDto>> groupVehicleMap = new ConcurrentHashMap<>();
            final List<VehicleGraphicsQueryListResDto> vehicleGraphicsList = results;
            vehicleGraphicsList.stream().forEach(vehicleDto -> {
                final String vin = vehicleDto.getVin();
                AtomicBoolean flag = new AtomicBoolean(false);
                followGroupList.entrySet().stream().filter(entry -> entry.getValue().contains(vin)).forEach(entry -> {
                    final String name = vehicleFollowGroupMap.get(Long.parseLong(entry.getKey()));
                    log.info("打印 关注组名称：{}",name);
                    if(groupVehicleMap.containsKey(name)){
                        groupVehicleMap.get(name).add(vehicleDto);
                    }else{
                        groupVehicleMap.put(name, new ArrayList<VehicleGraphicsQueryListResDto>(){{ add(vehicleDto); }});
                    }
                    flag.set(true);
                });
                if(!flag.get()){
                    if(groupVehicleMap.containsKey(DEFAULT_ATTENTION)){
                        groupVehicleMap.get(DEFAULT_ATTENTION).add(vehicleDto);
                    }else{
                        groupVehicleMap.put(DEFAULT_ATTENTION, new ArrayList<VehicleGraphicsQueryListResDto>(){{ add(vehicleDto); }});
                    }
                }
            });

            List<Map> resultMapList = new ArrayList<>();
            for (Map.Entry<String, List<VehicleGraphicsQueryListResDto>> entry : groupVehicleMap.entrySet()) {
                Map map  = new HashMap();
                map.put("province", entry.getKey());
                map.put("list", entry.getValue());
                resultMapList.add(map);
            }

            Map map = new HashMap();
            map.put("total", results.size());

            Collection<String> nameSet = vehicleFollowGroupMap.values();

            for (Map resultMap : resultMapList) {
                String province = (String)resultMap.get("province");
                nameSet.remove(province);
            }
            for (String name : nameSet) {
                Map a = new HashMap();
                a.put("province", name);
                a.put("list", new ArrayList());
                resultMapList.add(a);
            }
            List<Map>  resultList = new ArrayList<>();
            for(Map resultMap : resultMapList){
                String pro = (String)resultMap.get("province");
                Long groupId = vehicleFollowGroupNameIdMap.get(pro);
                resultMap.put("id",groupId);
                resultList.add(resultMap);
            }

            map.put("list", resultList);
            log.info("查询耗时: {} ms", Instant.now().minusMillis(instant.toEpochMilli()));
            return RestResponse.success(map);
        } catch (Exception e) {
            log.error("车辆监控 - 车辆管理 -图形列表-异常", e);
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 组装数据
     *
     * @param baseList            车辆基础信息
     * @param tboxModelMap        生产厂商+终端型号Map
     * @param commandMap          企业车机型号指令集合
     * @param onlineRestResponse  在线vin集合 key vin
     * @param positioningResponse 定位状态Map  key vin
     * @param reqDto              筛选条件
     */
    private List<VehicleGraphicsQueryListResDto> filterAttentionVehicleGraphics(List<VehicleBase> baseList, Map<String, Set<String>> followGroupList,
                                                                                Map<Long, String> vehicleFollowGroupMap,
            Map<String, String> tboxModelMap, Map<String, String> commandMap,
            RestResponse<List<String>> onlineRestResponse,
            RestResponse<Map<String, Boolean>> positioningResponse,
            Map<String, Integer> onlineReminderMap,
            VehicleGraphicsQueryListReqDto reqDto) {
        //结果集
        List<VehicleGraphicsQueryListResDto> results = new ArrayList<>();
        for (VehicleBase vehicleBase : baseList) {
            VehicleGraphicsQueryListResDto dto = new VehicleGraphicsQueryListResDto();
            String vin = vehicleBase.getVin();
            dto.setVin(vin);
            dto.setAuthorizedStatus(vehicleBase.getAuthorizedStatus());
            if (StringUtils.isNotBlank(vehicleBase.getLicense())) {
                dto.setLicense(vehicleBase.getLicense());
            } else {
                //如果没有车牌默认为0
                dto.setLicense("0");
            }
            String commandKey = genCompanyVehicleModelKey(vehicleBase, tboxModelMap);
            if (StringUtils.isNotBlank(commandKey) && commandMap != null && !commandMap.isEmpty()) {
                String s = commandMap.get(commandKey);
                List<VehicleCommand> vehicleCommands = JSON.parseArray(s, VehicleCommand.class);
                dto.setVehicleCommandList(vehicleCommands);
            }
            //在线
            if (RestResponse.isSuccess(onlineRestResponse)) {
                if (onlineRestResponse.getData().contains(vehicleBase.getVin())) {
                    dto.setOnLineStatus(OnLineStatusEnum.YES.getCode());
                } else {
                    dto.setOnLineStatus(OnLineStatusEnum.NO.getCode());
                }
            } else {
                //离线
                dto.setOnLineStatus(OnLineStatusEnum.NO.getCode());
            }
            if (RestResponse.isSuccess(positioningResponse)) {
                if (positioningResponse.getData().get(vehicleBase.getVin())) {
                    //已定位
                    dto.setPositioningState(PositioningStateEnum.YES.getCode());
                } else {
                    //未定位
                    dto.setPositioningState(PositioningStateEnum.NO.getCode());
                }
            } else {
                //未定位
                dto.setPositioningState(PositioningStateEnum.NO.getCode());
            }
            if(followGroupList != null){
                dto.setAttentionGroup(0L);
                dto.setAttentionGroupStr(DEFAULT_ATTENTION);
                followGroupList.entrySet().stream().filter(entry -> entry.getValue().contains(vin)).forEach(entry -> {
                    String key = entry.getKey();
                    final String seenKey = vehicleFollowGroupMap.get(Long.parseLong(key));
                    dto.setAttentionGroup(Long.parseLong(key));
                    dto.setAttentionGroupStr(seenKey);
                });
                if(dto.getAttentionGroup() != null &&
                        reqDto.getGroupId()!=null  &&
                        dto.getAttentionGroup().intValue() != reqDto.getGroupId().intValue()){
                    continue;
                }
            }
            if(onlineReminderMap != null && !onlineReminderMap.isEmpty() && onlineReminderMap.containsKey(vin)){
                dto.setOnlineReminder(onlineReminderMap.get(vin));
            }
            dto.setIsAttention(AttentionStatusEnum.YES.getCode());
            //条件筛选
            if (isCondition(dto, reqDto)) {
                results.add(dto);
            }
        }
        return results;
    }

    @Override
    public RestResponse listVehicleGraphicsQueryListRes(VehicleGraphicsQueryListReqDto reqDto) {
        log.info("车辆监控 - 车辆管理-图形树入参VehicleGraphicsQueryListReqDto:{}" + JSONObject.toJSONString(reqDto));
        ValidationUtils.validateBean(reqDto);
        try {
            Instant instant = Instant.now();
            //车辆
            List<VehicleBase> baseList = iVehicleBaseService.listVehicleBase();
            if (CollectionUtils.isEmpty(baseList)) {
                return RestResponse.success();
            }
            //得到所有的在线的车架号
            RestResponse<List<String>> onlineRestResponse = iRealService.queryAllOnlineList();
            ServiceValidation.validationService(onlineRestResponse, SysConstants.IOV_SERVICE_REAL);
            //得到tbox 生产厂商+终端型号
            Map<String, String> tboxModelMap = iVehicleTboxService.listVehicleTboxModelMap();
            //企业车机型号指令集合
            Map<String, String> commandMap = iCompanyVehicleModelService.listVehicleCommandMap();
            //得到所有的 定位状态
            //TODO  提供查找所有定位
            RestResponse<Map<String, Boolean>> locationVinMap = iRealService.isLocationVinMap(
                    baseList.stream().map(VehicleBase::getVin).collect(Collectors.toList()));
            ServiceValidation.validationService(locationVinMap, SysConstants.IOV_SERVICE_REAL);
            //拼装结果集
            List<VehicleGraphicsQueryListResDto> results = new ArrayList<>();

            if (UserTypeEnum.COMPANY.getFlag() == reqDto.getSysUserType().intValue()) {
                reqDto.setCompanyId(reqDto.getSysCompanyId());
                reqDto.setCompanyName(reqDto.getSysCompanyName());
            }

            Map<String, Set<String>> followGroupMap = iVehicleFollowGroupService.findVehicleFollowGroupByUserId(reqDto.getSysUserId());
            //平台用户并且公司Id为空
            if (UserTypeEnum.PLATFORM.getFlag() == reqDto.getSysUserType().intValue() && null == reqDto
                    .getCompanyId()) {
                results = listAssemblyVehicleGraphicsQueryListResDto(
                        baseList, tboxModelMap, commandMap,
                        onlineRestResponse, locationVinMap, reqDto,followGroupMap);
            } else {
                //企业用户 或者是 平台用户按公司查询
                List<VehicleBase> collect = baseList.stream().filter(
                        vehicleBase -> (reqDto.getCompanyId().longValue() == vehicleBase.getCompanyId()
                                .longValue())&&(AuthorizedEnum.AUTHORIZED.getCode()==vehicleBase.getAuthorizedStatus().intValue())).collect(
                        Collectors.toList());
                if (CollectionUtils.isEmpty(collect)) {
                    return RestResponse.success();
                }
                results = listAssemblyVehicleGraphicsQueryListResDto(
                        collect, tboxModelMap, commandMap,
                        onlineRestResponse, locationVinMap, reqDto,followGroupMap);
            }
            if (results.isEmpty()) {
                RestResponse.success();
            }
            List<Map> list = new ArrayList<>();

            Map<String, List<VehicleGraphicsQueryListResDto>> collect = results.stream()
                    .collect((Collectors.groupingBy(employee ->
                            employee.getLicense().substring(0, 1)
                    )));
            //无牌车辆
            List<VehicleGraphicsQueryListResDto> none = collect.get("0");
            collect.remove("0");
            collect.forEach((s, vehicleGraphicsQueryListResDtos) -> {
                Map map = new HashMap(2);
                map.put("province", s);
                map.put("list", vehicleGraphicsQueryListResDtos);
                list.add(map);
            });
            if (!CollectionUtils.isEmpty(none)){
                HashMap hashMap = new HashMap(2);
                hashMap.put("province", "无牌");
                hashMap.put("list", none);
                list.add(hashMap);
            }
            Map map = new HashMap(2);
            map.put("total", results.size());
            map.put("list", list);
            log.info("查询耗时: {} ms", Instant.now().minusMillis(instant.toEpochMilli()));
            return RestResponse.success(map);
        } catch (Exception e) {
            log.error("车辆监控 - 车辆管理 -图形列表-异常", e);
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public RestResponse queryAttentionVehicleList(QueryVehicleBaseListReqDto reqDto) {
        log.info("车辆监控 - 车辆管理-列表-入参QueryVehicleBaseListReqDto:{}" + JSONObject.toJSONString(reqDto));
        ValidationUtils.validateBean(reqDto);
        try {
            List<VehicleBaseQueryListResDto> results = new ArrayList<>();
            if (UserTypeEnum.COMPANY.getFlag() == reqDto.getSysUserType().intValue()) {
                reqDto.setCompanyId(reqDto.getSysCompanyId());
            }
            //已关注的车辆
            Map<String, Set<String>> followGroupList = iVehicleFollowGroupService.findVehicleFollowGroupByUserId(reqDto.getSysUserId());
            Map<Long, String> vehicleFollowGroupMap = iVehicleFollowGroupService.findNameByUserId(reqDto.getSysUserId());
            if (followGroupList == null || followGroupList.isEmpty()) {
                return RestResponse.success();
            }

            VehicleAttentionParam vehicleAttentionParam = new VehicleAttentionParam();
            vehicleAttentionParam.queryEqUserId(reqDto.getSysUserId());
            List<VehicleAttention> vehicleAttentionList = iVehicleAttentionService.list(vehicleAttentionParam.get());
            Map<String, Integer> onlineReminderMap = null;
            if (CollectionUtils.isEmpty(vehicleAttentionList)) {
                onlineReminderMap = vehicleAttentionList.stream().collect(Collectors.toMap(vehicleAttention -> vehicleAttention.getVin(),
                        vehicleAttention -> vehicleAttention.getOnlineReminder()));
            }

            List<String> vehicleNumberConditionList = new ArrayList<>();
            followGroupList.values().stream().forEach(followGroup -> vehicleNumberConditionList.addAll(followGroup));
            List<VehicleBase> baseList = iVehicleBaseService.lisVehicleBaseByVin(vehicleNumberConditionList).stream().collect(Collectors.toList());
            if (CollectionUtils.isEmpty(baseList)) {
                return RestResponse.success();
            }
            //得到tbox 生产厂商+终端型号
            Map<String, String> tboxModelMap = iVehicleTboxService.listVehicleTboxModelMap();
            //企业车机型号指令集合
            Map<String, String> commandMap = iCompanyVehicleModelService.listVehicleCommandMap();
            //已绑定的tbox
            Map<String, String> bindingMap = iVehicleTboxService.listVehicleTboxMap();
            //得到所有的在线的车架号
            RestResponse<List<String>> onlineRestResponse = iRealService.queryAllOnlineList();
            ServiceValidation.validationService(onlineRestResponse, SysConstants.IOV_SERVICE_REAL);
            //平台用户并且公司Id为空
            if (UserTypeEnum.PLATFORM.getFlag() == reqDto.getSysUserType().intValue() && null == reqDto.getCompanyId()) {
                List<String> vinList = baseList.stream().map(VehicleBase::getVin).collect(Collectors.toList());
                //TODO 平台用户定位状态
                RestResponse<Map<String, Boolean>> locationVinMap = iRealService.isLocationVinMap(vinList);
                ServiceValidation.validationService(locationVinMap, SysConstants.IOV_SERVICE_REAL);
                results = filterAttentionVehicleList(baseList, followGroupList, vehicleFollowGroupMap, bindingMap, onlineRestResponse, tboxModelMap,
                        commandMap, locationVinMap, onlineReminderMap, reqDto);
            } else {
                //企业用户 或者是 平台用户按公司查询
                List<VehicleBase> collect = baseList.stream().filter(vehicleBase -> reqDto.getCompanyId().longValue() == vehicleBase.getCompanyId().longValue()
                ).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(collect)) {
                    return RestResponse.success();
                }
                List<String> vinList = collect.stream().map(VehicleBase::getVin).collect(Collectors.toList());
                RestResponse<Map<String, Boolean>> locationVinMap = iRealService.isLocationVinMap(vinList);
                ServiceValidation.validationService(locationVinMap, SysConstants.IOV_SERVICE_REAL);
                results = filterAttentionVehicleList(collect, followGroupList, vehicleFollowGroupMap, bindingMap, onlineRestResponse, tboxModelMap,
                        commandMap, locationVinMap, onlineReminderMap, reqDto);
            }

            List<VehicleBaseQueryListResDto> collect = results.stream().sorted(Comparator.comparing(VehicleBaseQueryListResDto::getVin)).collect(Collectors.toList());
            Map<String, Object> pagingResultMap = PageUtils.getPagingResultMap(collect, reqDto.getPageNum().intValue(), reqDto.getPageSize().intValue());
            //组装车辆状态
            Map<String, Object> stringObjectMap = assembledAttentionVehicleState(pagingResultMap);
            return RestResponse.success(stringObjectMap);
        } catch (Exception e) {
            log.info("车辆监控 - 车辆管理-异常：{}", e);
            return RestResponse.failure("操作失败！");
        }
    }

    /**
     * 拼接数据返回符合结果
     *
     * @param base                车辆数据
     * @param followGroupList     关注组 关注组ID和车辆 vin集合
     * @param vehicleFollowGroupMap  关注组
     * @param bindingMap          已安装tbox  vin
     * @param onlineRestResponse  在线车辆 vin
     * @param tboxModelMap        得到tbox 生产厂商+终端型号
     * @param commandMap          企业车机型号指令集合
     * @param positioningResponse 定位状态
     * @param reqDto              查询参数
     */
    public List<VehicleBaseQueryListResDto> filterAttentionVehicleList(List<VehicleBase> base, Map<String, Set<String>> followGroupList,
                                                                       Map<Long, String> vehicleFollowGroupMap,
                                                                       Map<String, String> bindingMap,
                                                                       RestResponse<List<String>> onlineRestResponse,
                                                                       Map<String, String> tboxModelMap,
                                                                       Map<String, String> commandMap, RestResponse<Map<String, Boolean>> positioningResponse,
                                                                       Map<String, Integer> onlineReminderMap,
                                                                       QueryVehicleBaseListReqDto reqDto) {
        List<VehicleBaseQueryListResDto> results = new ArrayList<>();
        if (base == null || base.isEmpty()) {
            return results;
        }
        for (VehicleBase vehicleBase : base) {
            VehicleBaseQueryListResDto dto = new VehicleBaseQueryListResDto();
            CommonUtils.copyProperties(vehicleBase, dto);
            if (StringUtils.isNotBlank(vehicleBase.getLicense())) {
                dto.setLicense(vehicleBase.getLicense());
            } else {
                //如果没有车牌默认为0
                dto.setLicense("0");
            }

            String commandKey = genCompanyVehicleModelKey(vehicleBase, tboxModelMap);
            if (StringUtils.isNotBlank(commandKey) && commandMap != null && !commandMap.isEmpty()) {
                String s = commandMap.get(commandKey);
                List<VehicleCommand> vehicleCommands = JSON.parseArray(s, VehicleCommand.class);
                dto.setVehicleCommandList(vehicleCommands);
            }
            if (RestResponse.isSuccess(onlineRestResponse)) {
                //在线
                if (onlineRestResponse.getData().contains(vehicleBase.getVin())) {
                    dto.setOnLineStatus(OnLineStatusEnum.YES.getCode());
                    dto.setOnLineStatusStr(OnLineStatusEnum.YES.getCnName());
                } else {
                    //离线
                    dto.setOnLineStatus(OnLineStatusEnum.NO.getCode());
                    dto.setOnLineStatusStr(OnLineStatusEnum.NO.getCnName());
                }

            } else {
                //离线
                dto.setOnLineStatus(OnLineStatusEnum.NO.getCode());
                dto.setOnLineStatusStr(OnLineStatusEnum.NO.getCnName());
            }
            //TODO  确认定位接口
            if (RestResponse.isSuccess(positioningResponse)) {
                if (positioningResponse.getData().get(vehicleBase.getVin()) != null &&
                        positioningResponse.getData().get(vehicleBase.getVin())) {
                    //已定位
                    dto.setPositioningState(PositioningStateEnum.YES.getCode());
                } else {
                    //未定位
                    dto.setPositioningState(PositioningStateEnum.NO.getCode());
                }
            } else {
                //未定位
                dto.setPositioningState(PositioningStateEnum.NO.getCode());
            }
            final String vin = vehicleBase.getVin();
            if(followGroupList != null){
                dto.setAttentionGroup(0L);
                dto.setAttentionGroupStr(DEFAULT_ATTENTION);
                followGroupList.entrySet().stream().filter(entry -> entry.getValue().contains(vin)).forEach(entry -> {
                    String key = entry.getKey();
                    final String seenKey = vehicleFollowGroupMap.get(Long.parseLong(key));
                    dto.setAttentionGroup(Long.parseLong(key));
                    dto.setAttentionGroupStr(seenKey);
                });
                if(dto.getAttentionGroup() != null &&
                        reqDto.getGroupId()!=null  &&
                        dto.getAttentionGroup().intValue() != reqDto.getGroupId().intValue()){
                    continue;
                }
            }

            if(onlineReminderMap != null && !onlineReminderMap.isEmpty() && onlineReminderMap.containsKey(vin)){
                dto.setOnlineReminder(onlineReminderMap.get(vin));
            }

            if(reqDto.getOnlineReminder() != null && reqDto.getOnlineReminder().intValue() != dto.getOnlineReminder()){
                continue;
            }

            //登录授权状态
            if(reqDto.getLoginAuthorization() != null &&
                    reqDto.getLoginAuthorization().intValue() != dto.getLoginAuthorization()){
                continue;
            }

            //添加安装状态
            if (bindingMap != null && bindingMap.get(vehicleBase.getVin()) != null) {
                dto.setDeviceStatus(InstallStatusEnum.YES.getCode());
            } else {
                dto.setDeviceStatus(InstallStatusEnum.NO.getCode());
            }
            //条件筛选
            if (isCondition(dto, reqDto)) {
                results.add(dto);
            }
        }
        return results;
    }

    /**
     * 组装数据
     */
    private Map<String, Object> assembledAttentionVehicleState(Map<String, Object> pagingResultMap) {
        if (CollectionUtils.isEmpty(pagingResultMap)) {
            return new HashMap<>();
        }
        List<VehicleBaseQueryListResDto> resDtos = (List<VehicleBaseQueryListResDto>) pagingResultMap.get("records");
        if (!CollectionUtils.isEmpty(resDtos)) {
            List<String> vinList = resDtos.stream().map(VehicleBaseQueryListResDto::getVin).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(vinList)) {
                return pagingResultMap;
            }
            RestResponse<Map<String, VehicleStatusDto>> odoByVin = iRealService.getVehicleStatusByVin(vinList);
            ServiceValidation.validationService(odoByVin, SysConstants.IOV_SERVICE_REAL);

            for (VehicleBaseQueryListResDto dto : resDtos) {
                if (RestResponse.isSuccess(odoByVin)) {
                    VehicleStatusDto vehicleStatusDto = odoByVin.getData().get(dto.getVin());
                    if (vehicleStatusDto != null) {
                        dto.setReportDate(vehicleStatusDto.getReportDate());
                        if (vehicleStatusDto.getDynamicState() != null) {
                            dto.setPowerState(vehicleStatusDto.getDynamicState().getK());
                        }
                        if (vehicleStatusDto.getExtendPowerGear() != null) {
                            dto.setPowerStall(vehicleStatusDto.getExtendPowerGear().getK());
                        }
                        dto.setExtendGpsOde(vehicleStatusDto.getGpsOdo());
                        dto.setInstrumentMileage(vehicleStatusDto.getMeterOdo());
                        dto.setCumulativeMileage(vehicleStatusDto.getOdo());
                        if (vehicleStatusDto.getPhysicalKeyState() != null) {
                            dto.setKeyStatus(vehicleStatusDto.getPhysicalKeyState().getK());
                        }
                    }
                }
            }
            pagingResultMap.put("records", resDtos);
        }
        return pagingResultMap;
    }

    @Override
    public RestResponse listVehicleQueryListRes(QueryVehicleBaseListReqDto reqDto) {
        log.info("车辆监控 - 车辆管理-列表-入参QueryVehicleBaseListReqDto:{}" + JSONObject.toJSONString(reqDto));
        ValidationUtils.validateBean(reqDto);
        try {
            List<VehicleBaseQueryListResDto> results = assemblyVehicleBaseQueryListResDto(reqDto);
            List<VehicleBaseQueryListResDto> collect = results.stream().sorted(Comparator.comparing(VehicleBaseQueryListResDto::getVin)).collect(Collectors.toList());
            Map<String, Object> pagingResultMap = PageUtils.getPagingResultMap(collect, reqDto.getPageNum().intValue(), reqDto.getPageSize().intValue());
            //组装车辆状态
            Map<String, Object> stringObjectMap = assembledVehicleState(pagingResultMap);
            return RestResponse.success(stringObjectMap);
        } catch (Exception e) {
            log.info("车辆监控 - 车辆管理-异常：{}", e);
            return RestResponse.failure("操作失败！");
        }
    }

    /**
     * 组装数据
     */
    private Map<String, Object> assembledVehicleState(Map<String, Object> pagingResultMap) {
        if (CollectionUtils.isEmpty(pagingResultMap)) {
            return new HashMap<>();
        }
        List<VehicleBaseQueryListResDto> resDtos = (List<VehicleBaseQueryListResDto>) pagingResultMap.get("records");
        if (!CollectionUtils.isEmpty(resDtos)) {
            List<String> vinList = resDtos.stream().map(VehicleBaseQueryListResDto::getVin).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(vinList)) {
                return pagingResultMap;
            }
            RestResponse<Map<String, VehicleStatusDto>> odoByVin = iRealService.getVehicleStatusByVin(vinList);
            ServiceValidation.validationService(odoByVin, SysConstants.IOV_SERVICE_REAL);
            for (VehicleBaseQueryListResDto dto : resDtos) {
                if (RestResponse.isSuccess(odoByVin)) {
                    VehicleStatusDto vehicleStatusDto = odoByVin.getData().get(dto.getVin());
                    if (vehicleStatusDto != null) {
                        dto.setReportDate(vehicleStatusDto.getReportDate());
                        if (vehicleStatusDto.getDynamicState() != null) {
                            dto.setPowerState(vehicleStatusDto.getDynamicState().getK());
                        }
                        if (vehicleStatusDto.getExtendPowerGear() != null) {
                            dto.setPowerStall(vehicleStatusDto.getExtendPowerGear().getK());
                        }
                        dto.setExtendGpsOde(vehicleStatusDto.getGpsOdo());
                        dto.setInstrumentMileage(vehicleStatusDto.getMeterOdo());
                        dto.setCumulativeMileage(vehicleStatusDto.getOdo());
                        if (vehicleStatusDto.getPhysicalKeyState() != null) {
                            dto.setKeyStatus(vehicleStatusDto.getPhysicalKeyState().getK());
                        }
                    }
                }

            }

            pagingResultMap.put("records", resDtos);
        }
        return pagingResultMap;
    }

    @Override
    public RestResponse<VehicleBaseResDto> getVehicleCompanyIdByVin(String vin) {
        VehicleBase vehicleBaseByVin = iVehicleBaseService.getVehicleBaseByVin(vin);
        VehicleBaseResDto vehicleBaseResDto = new VehicleBaseResDto();
        CommonUtils.copyProperties(vehicleBaseByVin, vehicleBaseResDto);
        return RestResponse.success(vehicleBaseResDto);
    }

    @Override
    public Map<Long, List<String>> listVehicleBaseMap() {
        List<VehicleBase> vehicleBases = iVehicleBaseService.listVehicleBase();
        Map<Long, List<String>> collect = vehicleBases.stream().collect(Collectors.groupingBy(VehicleBase::getCompanyId,
                Collectors.mapping(VehicleBase::getVin, Collectors.toList())));
        return collect;

    }

    @Override
    public RestResponse<Map<String, VehicleBase>> listVehicleBaseByVin(List<String> vinList) {
        if (CollectionUtils.isEmpty(vinList)) {
            return RestResponse.failure("车架号不存在");
        } else {
            log.info(" 提供 报警统计查询实时入参vinList:{}" + vinList);
            List<String> distinct = vinList.stream().distinct().collect(Collectors.toList());
            List<VehicleBase> vehicleBases = iVehicleBaseService.lisVehicleBaseByVin(distinct);
            if (CollectionUtils.isEmpty(vehicleBases)) {
                return RestResponse.success();
            } else {
                Map<String, VehicleBase> collect = vehicleBases.stream().collect(Collectors.toMap(VehicleBase::getVin, vehicleBase -> vehicleBase));
                return RestResponse.success(collect);
            }
        }
    }

    @Override
    public RestResponse<String> queryLicenseByVin(String vin) {
        VehicleBase vehicleBaseByVin = iVehicleBaseService.getVehicleBaseByVin(vin);
        if (vehicleBaseByVin != null) {
            return RestResponse.success(vehicleBaseByVin.getLicense());
        } else {
            return RestResponse.success();
        }
    }

    @Override
    public RestResponse<String> queryVinByLicense(String license) {
        VehicleBase vehicleBaseByVin = iVehicleBaseService.queryVinByLicense(license);
        if (vehicleBaseByVin == null) {
            return RestResponse.success();
        } else {
            return RestResponse.success(vehicleBaseByVin.getVin());
        }
    }

    @Override
    public RestResponse<List<String>> listVinByCompanyId(Long companyId) {
        return iVehicleBaseService.listVinByCompanyId(companyId);
    }

    @Override
    public RestResponse vehicleBaseIsAuthorized(VehicleBaseAuthDto authDto) {
        ValidationUtils.validateBean(authDto);
        log.info("车联是否授权入参：{}",authDto);
        VehicleBase vehicleBase = iVehicleBaseService.getVehicleBaseByVin(authDto.getVin());
        if (vehicleBase==null){
            return RestResponse.failure("授权车辆不存在");
        }
        if (vehicleBase.getAuthorizedStatus().intValue()!=authDto.getAuthorizedStatus().intValue()){
            VehicleBaseReqDto dto = new VehicleBaseReqDto();
            CommonUtils.copyProperties(vehicleBase,dto);
            dto.setAuthorizedStatus(authDto.getAuthorizedStatus());
            return  iVehicleBaseService.updateVehicleBase(dto);
        }
        return RestResponse.success();
    }

    @Override
    public RestResponse<VehicleBase> queryVehicleBaseByLicense(String license) {
        VehicleBase vehicleBase = iVehicleBaseService.queryVinByLicense(license);
        return RestResponse.success(vehicleBase);
    }

    /**
     * 拼接车辆列表返回数据
     */
    public List<VehicleBaseQueryListResDto> assemblyVehicleBaseQueryListResDto(QueryVehicleBaseListReqDto reqDto) throws Exception {

        log.info("拼接车辆列表返回数据...");
        long start = System.currentTimeMillis();
        List<VehicleBaseQueryListResDto> results = new ArrayList<>();
        if (UserTypeEnum.COMPANY.getFlag() == reqDto.getSysUserType().intValue()) {
            reqDto.setCompanyId(reqDto.getSysCompanyId());
        }
        //车辆
        List<VehicleBase> baseList = iVehicleBaseService.listVehicleBase();
        //得到tbox 生产厂商+终端型号
        Map<String, String> tboxModelMap = iVehicleTboxService.listVehicleTboxModelMap();
        //企业车机型号指令集合
        Map<String, String> commandMap = iCompanyVehicleModelService.listVehicleCommandMap();
        //已绑定的tbox
        Map<String, String> bindingMap = iVehicleTboxService.listVehicleTboxMap();
        //得到所有的在线的车架号
        RestResponse<List<String>> onlineRestResponse = iRealService.queryAllOnlineList();
        ServiceValidation.validationService(onlineRestResponse, SysConstants.IOV_SERVICE_REAL);
        if (baseList == null || baseList.isEmpty()) {
            return results;
        }
        //得到所有的授权信息
        List<VehicleBaseAuth> authList = this.baseAuthService.listVehicleBaseAuth();
        Map<String,VehicleBaseAuth> authMap = new HashMap<>();
        if(authList!=null && authList.size()>0){
            for (VehicleBaseAuth vehicleBaseAuth : authList) {
                if(vehicleBaseAuth!=null && StringUtil.isNotBlank(vehicleBaseAuth.getVin())){
                    authMap.put(vehicleBaseAuth.getVin(),vehicleBaseAuth);
                }
            }
        }

        //平台用户并且公司Id为空
        if (UserTypeEnum.PLATFORM.getFlag() == reqDto.getSysUserType().intValue() && null == reqDto.getCompanyId()) {
            List<String> vinList = baseList.stream().map(VehicleBase::getVin).collect(Collectors.toList());
            //TODO 平台用户定位状态
            RestResponse<Map<String, Boolean>> locationVinMap = iRealService.isLocationVinMap(vinList);
            ServiceValidation.validationService(locationVinMap, SysConstants.IOV_SERVICE_REAL);
            results = splicingData(baseList, bindingMap, onlineRestResponse, tboxModelMap, commandMap, locationVinMap, reqDto,authMap);
        } else {
            //企业用户 或者是 平台用户按公司查询 对于企业用户，未授权车辆不可见
            List<VehicleBase> collect = baseList.stream().filter(vehicleBase ->
                    (reqDto.getCompanyId().longValue() == vehicleBase.getCompanyId().longValue())&&(AuthorizedEnum.AUTHORIZED.getCode()==vehicleBase.getAuthorizedStatus())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(collect)) {
                return results;
            }
            List<String> vinList = collect.stream().map(VehicleBase::getVin).collect(Collectors.toList());
            RestResponse<Map<String, Boolean>> locationVinMap = iRealService.isLocationVinMap(vinList);
            ServiceValidation.validationService(locationVinMap, SysConstants.IOV_SERVICE_REAL);
            results = splicingData(collect, bindingMap, onlineRestResponse, tboxModelMap, commandMap, locationVinMap, reqDto,authMap);
        }
        long end = System.currentTimeMillis();
        log.info("拼接车辆列表返回数据，执行时长：{}ms",end-start);
        return results;
    }

    /**
     * 拼接数据返回符合结果
     *
     * @param base                车辆数据
     * @param bindingMap          已安装tbox  vin
     * @param onlineRestResponse  在线车辆 vin
     * @param tboxModelMap        得到tbox 生产厂商+终端型号
     * @param commandMap          企业车机型号指令集合
     * @param positioningResponse 定位状态
     * @param reqDto              查询参数
     */
    public List<VehicleBaseQueryListResDto> splicingData(List<VehicleBase> base,
                                                         Map<String, String> bindingMap,
                                                         RestResponse<List<String>> onlineRestResponse,
                                                         Map<String, String> tboxModelMap,
                                                         Map<String, String> commandMap, RestResponse<Map<String, Boolean>> positioningResponse,
                                                         QueryVehicleBaseListReqDto reqDto,
                                                         Map<String,VehicleBaseAuth> authMap) {
        List<VehicleBaseQueryListResDto> results = new ArrayList<>();
        if (base == null || base.isEmpty()) {
            return results;
        }
        for (VehicleBase vehicleBase : base) {
            VehicleBaseQueryListResDto dto = new VehicleBaseQueryListResDto();
            CommonUtils.copyProperties(vehicleBase, dto);
            if (StringUtils.isNotBlank(vehicleBase.getLicense())) {
                dto.setLicense(vehicleBase.getLicense());
            } else {
                //如果没有车牌默认为0
                dto.setLicense("0");
            }
            String commandKey = genCompanyVehicleModelKey(vehicleBase, tboxModelMap);
            if (StringUtils.isNotBlank(commandKey) && commandMap != null && !commandMap.isEmpty()) {
                String s = commandMap.get(commandKey);
                List<VehicleCommand> vehicleCommands = JSON.parseArray(s, VehicleCommand.class);
                dto.setVehicleCommandList(vehicleCommands);
            }
            if (RestResponse.isSuccess(onlineRestResponse)) {
                //在线
                if (onlineRestResponse.getData().contains(vehicleBase.getVin())) {
                    dto.setOnLineStatus(OnLineStatusEnum.YES.getCode());
                    dto.setOnLineStatusStr(OnLineStatusEnum.YES.getCnName());
                } else {
                    //离线
                    dto.setOnLineStatus(OnLineStatusEnum.NO.getCode());
                    dto.setOnLineStatusStr(OnLineStatusEnum.NO.getCnName());
                }

            } else {
                //离线
                dto.setOnLineStatus(OnLineStatusEnum.NO.getCode());
                dto.setOnLineStatusStr(OnLineStatusEnum.NO.getCnName());
            }
            //TODO:  Confirm location interface
            if (RestResponse.isSuccess(positioningResponse)) {
                if (positioningResponse.getData().get(vehicleBase.getVin()) != null && positioningResponse.getData().get(vehicleBase.getVin())) {
                    //已定位
                    dto.setPositioningState(PositioningStateEnum.YES.getCode());
                } else {
                    //未定位
                    dto.setPositioningState(PositioningStateEnum.NO.getCode());
                }
            } else {
                //未定位
                dto.setPositioningState(PositioningStateEnum.NO.getCode());
            }
            //添加安装状态
            if (bindingMap != null && bindingMap.get(vehicleBase.getVin()) != null) {
                dto.setDeviceStatus(InstallStatusEnum.YES.getCode());
            } else {
                dto.setDeviceStatus(InstallStatusEnum.NO.getCode());
            }

            VehicleBaseAuth vehicleBaseAuth = authMap.get(vehicleBase.getVin());
            if(vehicleBaseAuth!=null){
                dto.setLoginAuthorization(vehicleBaseAuth.getLoginAuthStatus());
                dto.setLoginAuthorizationStr(dto.getLoginAuthorization().intValue() == 0 ? "不允许" : "允许");
                dto.setTerminalAlarm(vehicleBaseAuth.getTerminalAuthStatus());
                dto.setTerminalAlarmStr(dto.getTerminalAlarm().intValue() == 0 ? "不监控" : "监控");
                dto.setFenceAlarm(vehicleBaseAuth.getFenceAlarmAuthStatus());
                dto.setFenceAlarmStr(dto.getFenceAlarm().intValue() == 0 ? "不监控" : "监控");
                dto.setOfflineAlarm(vehicleBaseAuth.getLostAlarmAuthStatus());
                dto.setOfflineAlarmStr(dto.getOfflineAlarm().intValue() == 0 ? "不监控" : "监控");
                dto.setMileageChangeAlarm(vehicleBaseAuth.getMileageAlarmAuthStatus());
                dto.setMileageChangeAlarmStr(dto.getMileageChangeAlarm().intValue() == 0 ? "不监控" : "监控");
            }else{
                log.error("打印 授权信息：{}信息不存在",dto.getVin());
            }
            //条件筛选
            if (isCondition(dto, reqDto)) {
                results.add(dto);
            }
        }
        return results;
    }

    /**
     * 生产CompanyVehicleModelKey 公司id+品牌+车系+车型+ 车机生产商+ 车机型号 根据实体类生成唯一key
     */
    public String genCompanyVehicleModelKey(VehicleBase vehicleBase, Map<String, String> tboxModelMap) {
        if (vehicleBase != null && tboxModelMap != null && !tboxModelMap.isEmpty()) {
            StringBuffer sb = new StringBuffer();
            sb.append(vehicleBase.getCompanyId());
            sb.append(vehicleBase.getBrand());
            sb.append(vehicleBase.getVehicleSeries());
            sb.append(vehicleBase.getVehicleType());
            //tboxModelMap 包含   车机生产商+ 车机型号
            sb.append(tboxModelMap.get(vehicleBase.getVin()));
            return sb.toString();
        }
        return null;
    }

    /**
     * 组装数据
     *
     * @param baseList            车辆基础信息
     * @param tboxModelMap        生产厂商+终端型号Map
     * @param commandMap          企业车机型号指令集合
     * @param onlineRestResponse  在线vin集合 key vin
     * @param positioningResponse 定位状态Map  key vin
     * @param reqDto              筛选条件
     */
    private List<VehicleGraphicsQueryListResDto> listAssemblyVehicleGraphicsQueryListResDto(
            List<VehicleBase> baseList,
            Map<String, String> tboxModelMap, Map<String, String> commandMap,
            RestResponse<List<String>> onlineRestResponse,
            RestResponse<Map<String, Boolean>> positioningResponse,
            VehicleGraphicsQueryListReqDto reqDto,
            Map<String, Set<String>> followGroupMap) {
        if (baseList == null || baseList.isEmpty()) {
            return null;
        }

        Set<String> followGroupSet = new HashSet<>();
        Map<String,Long> followGroupMapVinGroupId = new HashMap<>();
        if(followGroupMap!=null){
            for (Map.Entry<String, Set<String>> entry : followGroupMap.entrySet()) {
                followGroupSet.addAll(entry.getValue());
                for (String vin : entry.getValue()) {
                    if(StringUtil.isNotBlank(vin) && entry.getValue()!=null){
                        followGroupMapVinGroupId.put(vin,Long.parseLong(entry.getKey()));
                    }
                }
            }
        }





        //结果集
        List<VehicleGraphicsQueryListResDto> results = new ArrayList<>();
        for (VehicleBase vehicleBase : baseList) {
            VehicleGraphicsQueryListResDto dto = new VehicleGraphicsQueryListResDto();
            String vin = vehicleBase.getVin();
            dto.setVin(vin);
            dto.setAuthorizedStatus(vehicleBase.getAuthorizedStatus());
            if (StringUtils.isNotBlank(vehicleBase.getLicense())) {
                dto.setLicense(vehicleBase.getLicense());
            } else {
                //如果没有车牌默认为0
                dto.setLicense("0");
            }
            String commandKey = genCompanyVehicleModelKey(vehicleBase, tboxModelMap);
            if (StringUtils.isNotBlank(commandKey) && commandMap != null && !commandMap.isEmpty()) {
                String s = commandMap.get(commandKey);
                List<VehicleCommand> vehicleCommands = JSON.parseArray(s, VehicleCommand.class);
                dto.setVehicleCommandList(vehicleCommands);
            }
            //在线
            if (RestResponse.isSuccess(onlineRestResponse)) {
                if (onlineRestResponse.getData().contains(vehicleBase.getVin())) {
                    dto.setOnLineStatus(OnLineStatusEnum.YES.getCode());
                } else {
                    dto.setOnLineStatus(OnLineStatusEnum.NO.getCode());
                }
            } else {
                //离线
                dto.setOnLineStatus(OnLineStatusEnum.NO.getCode());
            }
            if (RestResponse.isSuccess(positioningResponse)) {
                if (positioningResponse.getData().get(vehicleBase.getVin())) {
                    //已定位
                    dto.setPositioningState(PositioningStateEnum.YES.getCode());
                } else {
                    //未定位
                    dto.setPositioningState(PositioningStateEnum.NO.getCode());
                }
            } else {
                //未定位
                dto.setPositioningState(PositioningStateEnum.NO.getCode());
            }

            //添加关注状态
            if(followGroupSet.contains(dto.getVin())){
                dto.setIsAttention(AttentionStatusEnum.YES.getCode());
            }else{
                dto.setIsAttention(AttentionStatusEnum.NO.getCode());
            }
            //添加关注组
            if(followGroupMapVinGroupId!=null){
                dto.setAttentionGroup(followGroupMapVinGroupId.get(dto.getVin()));
            }

            //条件筛选
            if (isCondition(dto, reqDto)) {
                results.add(dto);
            }
        }
        return results;
    }

    /**
     * 筛选条件是否符合  图
     */
    public boolean isCondition(VehicleGraphicsQueryListResDto resDto, VehicleGraphicsQueryListReqDto reqDto) {
        if (reqDto.getOnLine() != null && resDto.getOnLineStatus().intValue() != reqDto.getOnLine().intValue()) {
            return false;
        }
        //TOdo 确定定位
        if (reqDto.getPositioningState() != null && resDto.getPositioningState().intValue() != reqDto.getPositioningState().intValue()) {
            return false;
        }
        if (reqDto.getQueryParam() != null && StringUtils.isNotBlank(reqDto.getQueryValue())) {
            if (QueryParamEnum.VIN.getCode() == reqDto.getQueryParam().intValue() && !resDto.getVin().contains(reqDto.getQueryValue())) {
                return false;
            }
            if (QueryParamEnum.LICENSE.getCode() == reqDto.getQueryParam().intValue() && !resDto.getLicense().contains(reqDto.getQueryValue())) {
                return false;
            }
        }
        return true;
    }

    /**
     * 筛选条件是否符合 列表
     */
    public boolean isCondition(VehicleBaseQueryListResDto resDto, QueryVehicleBaseListReqDto reqDto) {

        if (reqDto.getOnLineStatus() != null && resDto.getOnLineStatus().intValue() != reqDto.getOnLineStatus().intValue()) {
            return false;
        }
        //TODO: 确定定位
        if (reqDto.getPositioningState() != null && resDto.getPositioningState().intValue() != reqDto.getPositioningState().intValue()) {
            return false;
        }
        //设备安装
        if (reqDto.getDeviceStatus() != null && resDto.getDeviceStatus().intValue() != reqDto.getDeviceStatus()) {
            return false;
        }
        if (reqDto.getQueryParam() != null && StringUtils.isNotBlank(reqDto.getQueryValue())) {
            if (QueryParamEnum.VIN.getCode() == reqDto.getQueryParam().intValue() && !resDto.getVin().contains(reqDto.getQueryValue())) {
                return false;
            }
            if (QueryParamEnum.LICENSE.getCode() == reqDto.getQueryParam().intValue() && !resDto.getLicense().contains(reqDto.getQueryValue())) {
                return false;
            }
        }
        //过滤关键组
        if(reqDto.getGroupId()!=null && !reqDto.getGroupId().equals(resDto.getAttentionGroup())){
            return false;
        }
        //过滤登入授权
        if(reqDto.getLoginAuthorization()!=null && !reqDto.getLoginAuthorization().equals(resDto.getLoginAuthorization())){
            return false;
        }

        if(reqDto.getOnlineReminder()!=null && !reqDto.getOnlineReminder().equals(resDto.getOnlineReminder())){
            return  false;
        }
        return true;
    }

}
